import React, { forwardRef, useEffect, useRef, useImperativeHandle } from 'react';
import Quill, { QuillOptionsStatic } from 'quill';
import settings from '@/settings';

export interface RichtextProps {
  getContents: () => string;
  setContents: (contents: string) => void;
}

interface Props {
  readOnly?: boolean;
}

const Richtext = forwardRef<RichtextProps, Props>(({ readOnly }, ref) => {
  const richtext = useRef(null);
  const quill = useRef({} as Quill);

  useEffect(() => {
    if (richtext.current) {
      const options: QuillOptionsStatic = {
        modules: { toolbar: readOnly ? null : settings.toolbar },
        placeholder: readOnly ? '' : '请输入笔记内容...',
        theme: 'snow',
        readOnly,
      };
      quill.current = new Quill(richtext.current || '', options);
    }
  }, []);

  useImperativeHandle(ref, () => ({
    getContents: () => JSON.stringify(quill.current.getContents().ops),
    setContents: (contents: string) => quill.current.setContents(JSON.parse(contents || '[]')),
  }));

  return <article ref={richtext} />;
});

export default Richtext;
